package com.sziit.se.highconcurrency.common.tool;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class FormatFile {

    public static byte[] convertToPng(byte[] imageData) throws IOException {
        // 将byte[]转换为BufferedImage
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageData));

        // 如果bufferedImage为null，那么原始数据不是一个有效的图像格式
        if (bufferedImage == null) {
            throw new IOException("The input data is not a valid image format.");
        }

        // 创建一个ByteArrayOutputStream用于存储PNG数据
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();

        // 将BufferedImage写入PNG格式的数据到输出流
        ImageIO.write(bufferedImage, "PNG", pngOutputStream);

        // 将ByteArrayOutputStream的内容转换为byte[]并返回
        return pngOutputStream.toByteArray();
    }

}
